package com.donger.business.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donger.business.upms.entity.SysRole;
import com.donger.business.upms.entity.SysRoleMenu;
import com.donger.business.upms.mapper.SysRoleMapper;
import com.donger.business.upms.mapper.SysRoleMenuMapper;
import com.donger.business.upms.service.ISysRoleMenuService;
import com.donger.business.upms.service.ISysRoleService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 */
@Service("sysRoleService")
@AllArgsConstructor
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final SysRoleMenuMapper sysRoleMenuMapper;
    private final ISysRoleMenuService sysRoleMenuService;

    /**
     * 根据用户ID 查询角色列表
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> findRolesByUserId(Long userId) {
        return baseMapper.listRolesByUserId(userId);
    }

    /**
     * 保存更新角色权限
     * @param menuList 权限列表
     * @param roleId 角色id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveRoleMenu(List<Long> menuList, Long roleId) {
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId)
        );
        List<SysRoleMenu> list = menuList.stream().map(item -> {
            SysRoleMenu temp = new SysRoleMenu();
            temp.setPermsId(item);
            temp.setRoleId(roleId);
            return temp;
        }).collect(Collectors.toList());
        sysRoleMenuService.saveBatch(list);
        return Boolean.TRUE;
    }

    /**
     * 删除角色
     * 删除角色的同时删除和这个角色有关的权限
     * @param roleId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeRoleById(Long roleId) {
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,roleId));
        this.removeById(roleId);
        return Boolean.TRUE;
    }
}
